package com.tangyee.home_knowledge.dao;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

public class SearchRecordDAO {

    // 数据库变量,用于存放历史搜索记录
    private RecordSQLiteOpenHelper helper ;
    private SQLiteDatabase db;

    // 构造器，里面的两个变量从搜索页面传入
    public SearchRecordDAO(Context context){
        helper = new RecordSQLiteOpenHelper(context);
    }

    /**
     * listview设置适配器,利用适配器设置listview 的字体颜色
     * 模糊查询数据 & 显示到ListView列表上
     */
    public Cursor queryData(String tempName) {
        // 模糊搜索
        Cursor cursor = helper.getReadableDatabase().rawQuery(
                "select id as _id,name from records where name like '%" + tempName + "%' order by id desc ", null);

        return cursor;
    }

    /**
     * 清空数据库
     */
    public void deleteAllData() {
        db = helper.getWritableDatabase();
        db.execSQL("delete from records");
        db.close();
    }

    public void deleteADate(String tempName){
        db = helper.getWritableDatabase();
        db.execSQL("delete from records where name=" + "'" + tempName + "'");
        db.close();
    }

    /**
     * 检查数据库中是否已经有该搜索记录
     */
    public boolean isExist(String tempName) {
        // 从数据库中Record表里找到name=tempName的id
        Cursor cursor = helper.getReadableDatabase().rawQuery(
                "select id as _id,name from records where name =?", new String[]{tempName});
        //  判断是否有下一个
        return cursor.moveToNext();
    }

    /**
     * 插入数据到数据库，即写入搜索字段到历史搜索记录
     */
    public void insertData(String tempName) {
        db = helper.getWritableDatabase();
        db.execSQL("insert into records(name) values('" + tempName + "')");
        db.close();
    }
}
